﻿using MTQ.BLL;
using MTQ.Common;
using MTQ.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace MTQ.Web.Controllers
{
    /// <summary>
    /// 基类BaseController，过滤器
    /// </summary>
    [AccountAuth]
    public class BaseController : Controller
    {
        /// <summary>
        /// 当前登录的用户属性
        /// </summary>
        public Base_UserInfo CurrentUserInfo { get { return GetSession("UserInfo") as Base_UserInfo; } }


        //public List<string> UserControlProjectNumber { get { return GetSession("listProejctNumbers") as List<string>; } }
        public List<string> UserControlProjectNumber { get { return null; } }


        //public List<S_Menu> CurrentListUserMenu { get { return GetSession("userMenu") as List<S_Menu>; } }

        //public UserDataAccess CurrentUserDataAccess { get { return GetSession("UserDataAccess") as UserDataAccess; } }

        //public List<string> CurrentListUserAction { get { return Session["listUserAction"] as List<string>; } }



        private string _CultureInfoName;
        public string CultureInfoName
        {

            get
            {
                //System.Globalization.CultureInfo ci = (System.Globalization.CultureInfo)this.Session["CurrentLanguage"];
                return _CultureInfoName;
            }
        }

        /// <summary>
        /// 重新基类在Action执行之前的事情
        /// </summary>
        /// <param name="filterContext">重写方法的参数</param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            var selectStatusList = new List<SelectListItem>() {
                new SelectListItem() { Value = "Y", Text = "启用" },
                new SelectListItem() { Value = "N", Text = "禁用" }
                 };


            ViewBag.ListAvailable = selectStatusList;

            //if (Session==null || Session.Count== 0)
            //{
            //    var ret_url = filterContext.RequestContext.HttpContext.Request.Url.ToString();
            //    if (filterContext.HttpContext.Request.HttpMethod == "POST")
            //    {
            //        var result = new JsonResult();
            //        result.Data = new { state = 1, msg = "没有登陆或登陆超时", data = "/Login/Index?ret_url=" + ret_url };
            //        filterContext.Result = result;
            //    }
            //    else
            //    {
            //        //Response.Redirect("/Login/Index");
            //        var result = new ViewResult() { ViewName= "/Views/Login/Index.cshtml" };
            //        filterContext.Result = result;
            //    }
            //    //base.OnActionExecuting(filterContext);
            //    return;
            //}


            //多语言          
            //if (Session["CultureInfoName"] == null)
            //{
            //    string[] browerCulture = filterContext.HttpContext.Request.UserLanguages;
            //    if (browerCulture != null && browerCulture.Length > 0)
            //    {
            //        _CultureInfoName = browerCulture[0];
            //        ViewBag.CultureInfoName = _CultureInfoName;
            //    }
            //}
            //else
            //{
            //    _CultureInfoName = Session["CultureInfoName"].ToString();
            //    ViewBag.CultureInfoName = Session["CultureInfoName"].ToString(); 
            //}
            if (Session["CultureInfoName"] == null)
            {
                string[] browerCulture = filterContext.HttpContext.Request.UserLanguages;
                if (browerCulture != null && browerCulture.Length > 0)
                {
                    _CultureInfoName = browerCulture[0];
                    Session["CultureInfoName"] = browerCulture[0];
                }
            }
            else
            {
                _CultureInfoName = Session["CultureInfoName"].ToString();
            }


            ViewBag.Add = Base_LocalService.GetWord("Add", _CultureInfoName);
            ViewBag.Export = Base_LocalService.GetWord("Export", _CultureInfoName);
            ViewBag.Edit = Base_LocalService.GetWord("Edit", _CultureInfoName);
            ViewBag.Delete = Base_LocalService.GetWord("Delete", _CultureInfoName);
            ViewBag.Search = Base_LocalService.GetWord("Search", _CultureInfoName);
            ViewBag.SearchKey = Base_LocalService.GetWord("SearchKey", _CultureInfoName);
            ViewBag.ProjectNumber = Base_LocalService.GetWord("ProjectNumber", _CultureInfoName);
            ViewBag.Selected = Base_LocalService.GetWord("Selected", _CultureInfoName);
            ViewBag.AreYouSure = Base_LocalService.GetWord("AreYouSure", _CultureInfoName);
            ViewBag.PostError = Base_LocalService.GetWord("PostError", _CultureInfoName);
            ViewBag.Detail = Base_LocalService.GetWord("Detail", _CultureInfoName);
            ViewBag.StartDate = Base_LocalService.GetWord("StartDate", _CultureInfoName);
            ViewBag.LastDate = Base_LocalService.GetWord("LastDate", _CultureInfoName);
            ViewBag.TitleSearch = Base_LocalService.GetWord("TitleSearch", _CultureInfoName);
            ViewBag.Operation = Base_LocalService.GetWord("Operation", _CultureInfoName);
            ViewBag.Upload = Base_LocalService.GetWord("Upload", _CultureInfoName);
            ViewBag.Status = Base_LocalService.GetWord("Status", _CultureInfoName);
            ViewBag.Download = Base_LocalService.GetWord("Download", _CultureInfoName); 
            ViewBag.DownloadPdf = Base_LocalService.GetWord("DownloadPdf", _CultureInfoName);
            ViewBag.DownloadExcel = Base_LocalService.GetWord("DownloadExcel", _CultureInfoName);
            ViewBag.AddChild = Base_LocalService.GetWord("AddChild", _CultureInfoName);

            ViewBag.Freezing = Base_LocalService.GetWord("Freezing", _CultureInfoName);
            ViewBag.Thawing = Base_LocalService.GetWord("Thawing", _CultureInfoName);

            string controlName = ((filterContext.ActionDescriptor).ControllerDescriptor).ControllerName;
            string actionName = (filterContext.ActionDescriptor).ActionName;

            string word = "cn";
            if (CultureInfoName.IndexOf("en") > -1)
            {
                word = "en";
            }
            ViewBag.Language = word;


            //
            if (!(controlName == "Login"))
            {
                Base_UserInfo userInfo = this.CurrentUserInfo;
                //KeepSession();
                ViewBag.S_UserInfo = userInfo;
                if (userInfo == null)
                {
                    // Response.Redirect("/Login/Index");

                }
                else
                {
                    List<Base_Menu> listMenus = Session["listUserMenu"] as List<Base_Menu>;
                    Base_Menu pagemenus = listMenus.Where(x => x.Menu_NavigateUrl == ("" + controlName + "/" + actionName) || x.Menu_NavigateUrl == ("/" + controlName + "/" + actionName)).FirstOrDefault();
                    if (pagemenus != null)
                    {
                        List<Base_Button> base_Buttons = Session["listUserButtonIds"] as List<Base_Button>;

                        List<string> listButton_Code = base_Buttons.Where(x => x.Menu_Id == pagemenus.Menu_Id).Select(x => x.Button_Code).ToList();

                        ViewBag.listButton_Code = string.Join(",", listButton_Code) ;
                    }


                    base.OnActionExecuting(filterContext);
                }
            }
            else {
                

                base.OnActionExecuting(filterContext);
            }
        }
        private object GetSession(string name)
        {
            object obj = Session[name];
            if (obj == null)
            {
                var xrequestedwith = Request.Headers["x-requested-with"];
                if (xrequestedwith != null) {
                    // Response.Write("<script>alert()</script>");
                   
                    //throw new Exception("");
                }
                if (((System.Web.HttpResponseWrapper)Response).RedirectLocation != "/Login/Index") {
                    Response.Redirect("/Login/Index");
                }
               

            }


            return obj;
        }


        public string GetRequestQueryString(string key)
        {
            try
            {
                if (Request.QueryString[key] != null)
                {
                    return Request.QueryString[key];
                }
                else
                {
                    return Request.Form[key];
                }


            }
            catch
            {
                return null;
            }
        }


        /// <summary>
        /// 返回处理过的时间的Json字符串
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        /// 
        //[ProjectAuth(Roles = "Base_JsonDate")]
        public ContentResult JsonDate(object date)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return Content(JsonConvert.SerializeObject(date, Formatting.Indented, timeConverter));
        }

        /// <summary>   
        /// 去掉网页中的html标签   
        /// </summary>   
        /// <param name="strHtml">待转化的字符串</param>   
        /// <returns></returns>   
        public static string stripHtml(string strHtml)
        {
            Regex objRegExp = new Regex("<(.|/n)+?>");
            string strOutput = objRegExp.Replace(strHtml, "");
            strOutput = strOutput.Replace("<", "<");
            strOutput = strOutput.Replace(">", ">");
            return strOutput;
        }



    }



}
